import Types from '../types'
import DataStore, {FLAG_STORAGE} from '../../expand/dao/DataStore'
import {handleData} from "../actionUtil";
import {_projectModels} from "../actionUtil";

/**
 * 获取最热数据的异步action
 * @param theme
 * @return {{type: string, theme: *}}
 */
export const onRefreshTrending = (storeName, url, pageSize, favoriteDao, isLoading) => {
    return dispatch => {
        if (isLoading) {
            dispatch({
                type: Types.TRENDING_REFRESH,
                storeName: storeName
            })
        }

        let dataStore = new DataStore()
        dataStore.fetchData(url, FLAG_STORAGE.flag_trending) //异步action与数据流
            .then(data => {
                handleData(Types.TRENDING_REFRESH_SUCCESS, dispatch, storeName, data, pageSize, favoriteDao)
            }).catch(error => {
            console.log(error)
            dispatch({
                type: Types.TRENDING_REFRESH_FAIL,
                storeName,
                error,
            })
        })
    }
}
/**
 * 加载更多数据
 * @param storeName
 * @param pageIndex
 * @param pageSize
 * @param dataArray
 * @param callBack
 * @return {Function}
 */
export const onLoadMoreTrending = (storeName, pageIndex, pageSize, dataArray = [], favoriteDao, callBack) => {
    return dispatch => {
        setTimeout(() => {
            if ((pageIndex - 1) * pageSize >= dataArray.length) { //已经加载完全部数据
                if (typeof callBack === 'function') {
                    callBack('no more')
                }
                dispatch({
                    type: Types.TRENDING_LOAD_MORE_FAIL,
                    error: 'no more',
                    storeName,
                    pageIndex: --pageIndex,
                    projectModels: dataArray
                })
            } else {
                let max = pageIndex * pageSize > dataArray.length ? dataArray.length : pageIndex * pageSize
                _projectModels(dataArray.slice(0, max), favoriteDao, projectModels => {
                    dispatch({
                        type: Types.TRENDING_LOAD_MORE_SUCCESS,
                        storeName,
                        pageIndex,
                        projectModels,
                    })
                })
            }
        }, 500)
    }
}


